package com.baocaiqiche.dev.taoforandroid;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener{

    private static final int TYPE_ITEM = 0;
    private static final int TYPE_FOOTER = 1;
    private OnItemClickListener mOnItemClickListener = null;
    public ArrayList<User> datas = new ArrayList<>();


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_item,parent,false);
        view.setOnClickListener(this);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        User user = datas.get(position);
        holder.textNameView.setText(user.getName());
        holder.textMobile.setText(user.getMobile());
        holder.itemView.setTag(position);
    }

    @Override
    public int getItemCount() {
        return datas.size();
    }

    @Override
    public void onClick(View view) {
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(view,(int)view.getTag());
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        private TextView textNameView , textMobile;

        public ViewHolder(View itemView) {
            super(itemView);
            textNameView = itemView.findViewById(R.id.userNameItem);
            textMobile = itemView.findViewById(R.id.userMobileItem);
        }

    }

    //添加数据
    public void addItem(ArrayList<User> newDatas) {
        datas.addAll(newDatas);
        notifyDataSetChanged();
    }

    public void addMoreItem(ArrayList<User> newDatas) {

        ArrayList<User> mList = new ArrayList<User>();
        mList = newDatas;
        mList.addAll(datas);
        datas = mList;
        mList = null;
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    //define interface
    public static interface OnItemClickListener {
        void onItemClick(View view , int position);
    }
}
